package com.txsj.scan.presenter;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.google.gson.Gson;
import com.greendao.GoodsInfoDao;
import com.greendao.RecordInfoDao;
import com.txsj.scan.Constants;
import com.txsj.scan.base.BasePresenter;
import com.txsj.scan.bean.BaseListResult;
import com.txsj.scan.bean.EpcTagBean;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.RecordInfo;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.http.ApiServer;
import com.txsj.scan.http.UrlInterface;
import com.txsj.scan.http.requestframework.RetrofitManager;
import com.txsj.scan.utils.GZIPUtils;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.utils.MD5Util;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.view.IWarehouseDetailView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class WareHousePresenter extends BasePresenter<IWarehouseDetailView> {

    private static final int ON_SUCCESS = 0x091;
    private static final int ON_LOADING = 0x092;
    private static final int ON_ERROR = 0x093;

    private WarehouseBean warehouseBean;
    private List<RecordInfo> recordInfoList;
    private long times_long = 1000 * 60 * 30;//时间差
//    private long times_long = 1000*30;//时间差

    private long time_difference = 0;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case ON_LOADING:
                    if (null != view)
                        view.onLoading();
                    break;
                case ON_SUCCESS:
                    if (null != view)
                        view.onSuccess();
                    break;
                case ON_ERROR:
                    if (null != view)
                        view.onError("网络异常");
                    break;
            }
        }
    };

    public WareHousePresenter(IWarehouseDetailView view) {
        super(view);
    }

    @Override
    protected void initModel() {

    }

    /**
     * 如果第一次进入本仓库，说明该仓库下的商品数据还没有进行缓存
     *
     * @param warehouseBean
     */
    public void getGoodsList(WarehouseBean warehouseBean) {
        this.warehouseBean = warehouseBean;
        recordInfoList = GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().queryBuilder()
                .where(RecordInfoDao.Properties.Type.eq(Constants.GOODS_INFO)
                        , RecordInfoDao.Properties.Warehouse_id.eq(warehouseBean.getWarehouse_id()))
                .list();
        if (null == recordInfoList || recordInfoList.size() == 0) {//如果为空说明是第一次进来直接进行缓存
            gotoHttpData();
        } else {
            if (System.currentTimeMillis() - recordInfoList.get(0).getUpdate_time() >= times_long) {
                gotoHttpData();
                Trace.e("wcj更新时间：======" + recordInfoList.get(0).getUpdate_time());
            }
        }
    }

    /**
     * 开线程缓存商品数据
     */
    private void gotoHttpData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                getGoodsListAndCache();
                Looper.loop();
            }
        }).start();
    }





    /**
     * 缓存商品数据
     */
    private void getGoodsListAndCache() {
        Map<String, String> params = RetrofitManager.getParams();
        params.put("page", "0");//page=0，不分页
        params.put("limit", 200 + "");
        params.put("warehouse_id", warehouseBean.getWarehouse_id() + "");

        Map<String, String> header = RetrofitManager.getHeader();
        header.put("gzip_type", "1");
        handler.sendEmptyMessage(ON_LOADING);
        RetrofitManager.getDefault().create(ApiServer.class).getGoodsInventoryBytesList(header, params)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (null != response && null != response.body()) {
                                if (null != response.body().source() && response.isSuccessful()) {
                                    //获得response中的body的字节数组
//                                    byte[] data = response.body().bytes();
                                    //通过UTF-8解压缩成json字符串
                                    String json = GZIPUtils.uncompressToString(response.body().source().readByteArray(), GZIPUtils.GZIP_ENCODE_UTF_8);
                                    //将字符串转换成定义好的数据类型
                                    final JSONObject jsonObject = new JSONObject(json);

                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            updateGoodsInfo(jsonObject);
                                        }
                                    }).start();

                                } else {
                                    handler.sendEmptyMessage(ON_ERROR);
                                }
                            } else {
                                handler.sendEmptyMessage(ON_ERROR);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Trace.e("" + t.getMessage());
                        handler.sendEmptyMessage(ON_ERROR);
                    }
                });
    }

    private void updateGoodsInfo(JSONObject jsonObject) {
        Trace.e(jsonObject.toString());
        // 对数据进行操作
        boolean isSuccess = jsonObject.optBoolean("success");
        if (isSuccess) {
            JSONArray jsonArray = jsonObject.optJSONArray("data");
            List<GoodsInfo> list = GsonFactory.getObjectList(jsonArray.toString(), GoodsInfo.class);
            if (null != list && list.size() > 0) {
                setDataToDatabase(list);
            }
            handler.sendEmptyMessage(ON_SUCCESS);
        } else {
            handler.sendEmptyMessage(ON_ERROR);
        }
    }

    /**
     * 将读取完毕的数据缓存到数据库
     */
    private void setDataToDatabase(List<GoodsInfo> goodsInfos) {
        GoodsInfoDao goodsInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao();
        //先查询当前仓库下的商品
        List<GoodsInfo> list = goodsInfoDao.queryBuilder()
                .where(GoodsInfoDao.Properties.Warehouse_id.eq(warehouseBean.getWarehouse_id()))
                .list();
        //通过遍历删除
        for (GoodsInfo info : list) {
            goodsInfoDao.delete(info);
        }
        //循环新的商品数据添加
        for (GoodsInfo goodsInfo : goodsInfos) {
            goodsInfo.setWarehouse_id(warehouseBean.getWarehouse_id() + "");//将请求回来的数据添加上warehouseid
        }

        goodsInfoDao.insertOrReplaceInTx(goodsInfos);
        //对更新后的数据进行记录
        if (null == recordInfoList || recordInfoList.size() == 0) {
            RecordInfo recordInfo = new RecordInfo();
            recordInfo.setType(Constants.GOODS_INFO);
            recordInfo.setUpdate_time(System.currentTimeMillis());
            recordInfo.setWarehouse_id(warehouseBean.getWarehouse_id() + "");
            GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().insertOrReplace(recordInfo);
        } else {
            if (System.currentTimeMillis() - recordInfoList.get(0).getUpdate_time() >= times_long) {
                recordInfoList.get(0).setUpdate_time(System.currentTimeMillis());
                GreenDaoUtils.getSingleTon().getmDaoSession().getRecordInfoDao().insertOrReplace(recordInfoList.get(0));
                Trace.e("wcj最新更新时间：======" + recordInfoList.get(0).getUpdate_time());
            }
        }
    }
}
